import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/blind_model/list_by_blindId_count_model.dart';
import 'package:yysk_app/model/blind_model/list_by_blindId_model.dart';
import 'package:yysk_app/model/blind_model/open_blind_model.dart';
import 'package:yysk_app/model/collection_model/my_collection_list_by_collection_id_head_model.dart';
import 'package:yysk_app/model/collection_model/my_collection_list_by_collection_id_model.dart';
import 'package:yysk_app/net/api/api_url.dart';

import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';

class MyBlindListController extends GetxController {
  int pageNum = 1;
  int pageSize = 10;
  final ScrollController scrollController = ScrollController();
  late String boxId;
  late String boxName;
  final count = RxInt(0);
  final whether = RxBool(false);//transferableStatus
   final transferableStatus = RxBool(false);//transferableStatus
  final list = RxList<ListByBlindIdItem>([]);
  final openBlindDetail = Rx<OpenBlindModel?>(null);

  @override
  void onInit() {
    super.onInit();
    final params = Get.parameters ?? {};
    final args = Get.arguments ?? {};
    boxId = params['boxId'] ?? args['boxId'];
    boxName = params['boxName'] ?? args['boxName'];
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getBlindList(loadMore: true);
        getCount();
      }
    });
    getBlindList();
    getCount();
  }

  @override
  void onClose() {
    super.onClose();
    Get.delete<ScrollController>(); //删除控制器实例
    scrollController.dispose();
  }

  void getCount() {
    http.netFetch<ListByBlindIdCountModel>(
      ApiUrl.countByBoxId,
      params: {'boxId': boxId},
      success: (result) {
        count.value = result.data!.count ?? 0;
        whether.value = result.data!.whether ?? false;
        transferableStatus.value = result.data!.transferableStatus??false;
      },
    );
  }

  getBlindList({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      http.netFetch<ListByBlindIdModel>(
        ApiUrl.boxListByBoxId,
        params: {'pageNum': pageNum, 'pageSize': 20, 'boxId': boxId},
        success: (result) {
          List<ListByBlindIdItem> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            list.clear();
          }
          list.addAll(items);
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }

  Future openBlind() async {
    return await http.netFetch<OpenBlindModel>(
      ApiUrl.openUserBox,
      params: {'boxId': boxId},
      success: (result) {
        openBlindDetail.value = result.data;
      },
    );
  }
}
